﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace YH.Bluetooth
{
    public class SLPWrapper
    {
        [DllImport("slp.dll",
       CallingConvention = CallingConvention.Cdecl,
       CharSet = CharSet.Ansi)]
        private static extern IntPtr m_SLPInterface(
       int action,
       [In] float[] eegdata = null,
       int eegdata_len = 0,
       [In] float[] acc_x = null,
       int acc_x_len = 0,
       [In] float[] acc_y = null,
       int acc_y_len = 0,
       [In] float[] acc_z = null,
       int acc_z_len = 0,
       float pickupdata_time = 0.0f
   );

        public string CalculateSLP(float[] eegData, float[] accX, float[] accY, float[] accZ, float pickupTime)
        {
            if (eegData == null)
            {
                throw new ArgumentNullException(nameof(eegData));
            }
            if (accX == null)
            {
                throw new ArgumentNullException(nameof(accX));
            }
            if (accY == null)
            {
                throw new ArgumentNullException(nameof(accY));
            }
            if (accZ == null)
            {
                throw new ArgumentNullException(nameof(accZ));
            }
            try
            {
                var resultPtr = m_SLPInterface(
                    1,
                    eegData, eegData.Length,
                    accX, accX.Length,
                    accY, accY.Length,
                    accZ, accZ.Length,
                    pickupTime
                );

                return Marshal.PtrToStringAnsi(resultPtr) ?? "Error: Could not convert result";
            }
            catch (Exception ex)
            {
                return $"Error: {ex.Message}";
            }
        }

        public string InitializeSLP() =>
            Marshal.PtrToStringAnsi(m_SLPInterface(0));

        public string DestroySLP() =>
            Marshal.PtrToStringAnsi(m_SLPInterface(2));
    }
}
